<template>
  <div>
    <el-form
      :model="user"
      :rules="rules"
      ref="userForm"
      label-width="80px"
      style="width: 70%"
    >
      <el-form-item :label="$t('common.name')" prop="userName">
        <el-input v-model="user.userName"></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.email')" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.phone')" prop="phoneNumber">
        <el-input v-model="user.phoneNumber"></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('common.role')"
        prop="roleNames"
        v-if="showRoleSelect"
      >
        <roleSelect
          :multiple="true"
          v-model="user.roleNames"
          :roleIds.sync="user.roleIds"
        ></roleSelect>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel" size="small">取消</el-button>
      <el-button type="primary" @click="handleSubmit" size="small"
        >确定</el-button
      >
    </div>
  </div>
</template>
<script>
import roleSelect from "@/components/Select/roleSelect";
import { getUser, getUserRoles, addUser, updateUser } from "@/api/user";
export default {
  components: {
    roleSelect,
  },
  data() {
    return {
      user: {
        userName: "",
        email: "",
        phoneNumber: "",
        roleNames: [],
        roleIds: [],
      },
      rules: {
        userName: [
          {
            required: true,
            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        roleNames: [
          {
            validator: this.roleValidator,
            trigger: "blur",
          },
        ],
      },
      showRoleSelect: false,
    };
  },
  methods: {
    getUserRoles() {
      if (!this.userId) {
        this.showRoleSelect = true;
        return;
      }

      getUserRoles(this.userId).then((res) => {
        let roles = res ? res.items : [];
        this.user.roleNames = roles.map((role) => {
          return role.name;
        });
        this.user.roleIds = roles.map((role) => {
          return role.id;
        });
        this.showRoleSelect = true;
      });
    },
    getUserData() {
      if (!this.userId) {
        this.showRoleSelect = true;
        return;
      }
      getUser(this.userId).then((res) => {
        this.user = res || {};
        this.user.roleIds = [];
        this.getUserRoles();
      });
    },
    handleSubmit() {
      this.$refs["userForm"].validate((valid) => {
        if (valid) {
          this.saveData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveData() {
      if (!this.userId) {
        this.user.password = "1q2w3E*";
        addUser(this.user).then((res) => {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("success", res);
        });
      } else {
        updateUser(this.user).then((res) => {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("success", res);
        });
      }
    },
    roleValidator(rule, value, callback) {
      if (!this.user.roleNames || this.user.roleNames.length == 0) {
        let tips = this.$t("tips.requireItem");
        callback(new Error(tips));
      } else callback();
    },
    handleCancel() {
      this.$emit("close");
    },
  },
  created() {
    this.getUserData();
  },
  mounted() {
    //this.getUserData();
  },
  computed: {
    userId() {
      return this.id || "";
    },
  },
  props: {
    id: {
      type: String,
      default: null,
    },
  },
};
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
